<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>互阅侠管理系统</h2>
      </div>
      <div class="login-form">
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="0">
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="用户名" 
              prefix-icon="User"
              size="large"
            />
          </el-form-item>
          <el-form-item prop="passwordHash">
            <el-input 
              v-model="loginForm.passwordHash" 
              type="password" 
              placeholder="密码" 
              prefix-icon="Lock"
              size="large"
              show-password
              @keyup.enter="handleLogin"
            />
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              :loading="loading" 
              @click="handleLogin" 
              size="large"
              style="width: 100%"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginApi } from '../api/login'
import { useUserStore } from '../store/user'

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loading = ref(false)

// 登录表单数据
const loginForm = reactive({
  username: '',
  passwordHash: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  passwordHash: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await loginApi(loginForm).then(res=>{
          console.log('登录响应:', res)
          if (res && res.code === 1) {
            // 确保res.data包含token
            if (!res.data || !res.data.token) {
              console.warn('登录响应中缺少token:', res.data)
              // 如果后端没有返回token，可以设置一个临时token用于测试
              if (res.data) {
                res.data.token = 'temp-token-' + Date.now()
              }
            }
            
            // 保存到localStorage
            localStorage.setItem("loginUser", JSON.stringify(res.data))
            
            // 同时更新Pinia store
            userStore.setUserInfo(res.data)
            userStore.setToken(res.data.token)
            
            ElMessage.success('登录成功')
            
            // 获取重定向地址
            const redirect = router.currentRoute.value.query.redirect || '/'
            router.push(redirect)
          } else {
            ElMessage.error(res?.message || '登录失败，请检查用户名和密码')
          }
        }).catch(error=>{
          console.error('登录请求错误:', error)
          ElMessage.error('登录请求失败，请检查网络连接')
        })
        
      } catch (error) {
        ElMessage.error('登录失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="less">
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
  
  .login-box {
    width: 400px;
    padding: 40px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .login-header {
      text-align: center;
      margin-bottom: 40px;
      
      h2 {
        font-size: 24px;
        color: #303133;
        margin: 0;
      }
    }
    
    .login-form {
      margin-top: 20px;
    }
  }
}
</style>